# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError, RepeatNotifyError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '16019': {
        #  金鱼支付 支付宝 3.5% 50-5000 dwc
        'API_KEY': '02d56da83149e3885421a56061f981b2',
        'gateway': 'https://polo.zhaozhizuo.cn/api/rechg/topay',
        'query_gateway': 'https://polo.zhaozhizuo.cn/api/rechg/order/queryOrder?mercId={}&tradeNo={}',
    },
    '13199': {
        #  金鱼支付 支付宝 2.5% 100-5000 dwc
        'API_KEY': '7292b3eb4e871006374ca11abfa27172',
        'gateway': 'https://polo.zhaozhizuo.cn/api/rechg/topay',
        'query_gateway': 'https://polo.zhaozhizuo.cn/api/rechg/order/queryOrder?mercId={}&tradeNo={}',
    },
    '10147': {
        #  金鱼支付 银联 2.5% 100-5000 dwc
        'API_KEY': '6a4984f2b99faa9657af684c914a58b2',
        'gateway': 'https://uket.tdhvdn.cn/api/union/topay',
        'query_gateway': 'https://uket.tdhvdn.cn/api/union/order/queryOrder?mercId={}&tradeNo={}',
    },
    '10175': {
        #  金鱼支付 支付宝 2.5% 100-5000 dwc
        'API_KEY': '597179d2eb38152fdc49410cd2e46128',
        'gateway': 'https://dava.paixueshuan.cn/api/rechg/topay',
        'query_gateway': 'https://dava.paixueshuan.cn/api/rechg/order/queryOrder?mercId={}&tradeNo={}',
    },
    '15924': {
        #  金鱼支付 支付宝 2.5% 100-5000 witch
        'API_KEY': '2fe3415c0f2bca76641de834ba6ba92b',
        'gateway': 'https://polo.zhaozhizuo.cn/api/rechg/topay',
        'query_gateway': 'https://polo.zhaozhizuo.cn/api/rechg/order/queryOrder?mercId={}&tradeNo={}',
    },
    '11027': {
        #  金鱼支付 云闪付 2.5% 100-5000 witch
        'API_KEY': '270c03e7e961803cdecae563abf75797',
        'gateway': 'https://uket.tdhvdn.cn/api/union/topay',
        'query_gateway': 'https://uket.tdhvdn.cn/api/union/order/queryOrder?mercId={}&tradeNo={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def gen_order_sign(d, key):
    s = '{}{}{}{}{}{}'.format(
        d['mercId'], d['money'], d['notifyUrl'], d['tradeNo'], d['type'], key
    )
    return _gen_sign(s)


def gen_order_rsp_sign(d, key):
    s = '{}{}{}'.format(
        d['oid'], d['payUrl'], key
    )
    return _gen_sign(s)


def gen_notify_sign(d, key):
    s = '{}{}{}{}{}{}'.format(
        d['code'], d['mercId'], d['oid'], d['payMoney'], d['tradeNo'], key
    )
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = gen_order_rsp_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jinyupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = gen_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jinyupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    elif service == 'wechat':
        return 'wechat'
    elif service == 'unionpay':
        return 'unionPay'
    return 'alipay'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '219.135.56.195'


def _get_device_id(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_id') or 'IMEI00000001111112222222'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})

    parameter_dict = OrderedDict((
        ('mercId', app_id),
        ('tradeNo', str(pay.id)),
        ('type', _get_pay_type(service)),
        ('money', '%.2f' % pay_amount),
        ('notifyUrl', '{}/pay/api/{}/jinyupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('time', str(int(round(time.time() * 1000)))),
        ('info', {
            'playerId': str(pay.user_id),
            'playerIp': _get_device_ip(info),
            'deviceId': _get_device_id(info),
            'deviceType': user_info.get('device_type') or 'android',
        }),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("jinyupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['tradeNo'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("jinyupay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)['msg']
    verify_sign(data, api_key)
    return {'charge_info': data['payUrl']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("jinyupay notify data: %s, order_id is: %s", data, data['tradeNo'])
    verify_notify_sign(data, api_key)
    pay_id = data['tradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('jinyupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise RepeatNotifyError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['oid']
    total_fee = float(data['payMoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,00-交易成功
    if trade_status == '200':
        _LOGGER.info('jinyupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('mercId', app_id),
        ('tradeNo', str(pay_id)),
    ))
    _LOGGER.info("jinyupay query data: %s, order_id: %s", json.dumps(parameter_dict), parameter_dict['tradeNo'])
    url = _get_query_gateway(app_id).format(parameter_dict['mercId'], parameter_dict['tradeNo'])
    _LOGGER.info('jinyupay query data, %s', url)
    response = requests.get(url, timeout=3)
    _LOGGER.info("jinyupay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = unicode(data['msg']['payStatus'])
        trade_no = pay_order.third_id
        total_fee = float(data['msg']['payMoney'])
        # total_fee = float(data['msg']['money'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 交易成功 200
        if trade_status == u'已支付':
            _LOGGER.info('jinyupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jinyupay data error, status_code: %s', response.status_code)
